/***
 * 公司资料js
 * 20151025
 */
$(function() {
	// 渲染页面-通用部分；
	commTemplUtil.initPage();
	// 渲染左侧菜单;
	commTemplUtil.initCommLeftMemu();
	
	//初始公司信息
	iniClassifyData();
	
	//验证公司基本资料的表单及提交
	validateMainForm();
	
	//验证修改密码的表单及提交
	validatePwdForm();
	//验证修改邮件的表单及提交
	validateEmailForm();
});

//地区下拉框
var areaTemplObj = _.template($('#area-option-templ').html());

//初始公司信息
function iniClassifyData(){
	
	//渲染省
	$.ajax({
		url : PAGE_CONFIG.requestUrl.addrProvince,
		type : 'get',
		dataType : 'json',
		success : function (result) {
			var datas = $.extend([], result.data);
			var tmplObjHtml = areaTemplObj(datas);
			$("#province").html(tmplObjHtml);
		},
		error : function (xhr, status, error) {
			var tmplObjHtml = areaTemplObj([]);
			$("#province").html(tmplObjHtml);
		}
	});

	$("#province").on("change", function () {
	    var code = $(this).val();
	    renderAddrCity(code);
	});

	$("#city").on("change", function () {
	    var code = $(this).val();
	    renderAddrCounty(code);
	});
	
	// 获取公司资料
	$.ajax({
		url : PAGE_CONFIG.requestUrl.queryCompany,
		type : "get",
		data : {
			id : 1,
			_token : COMM_DATA.csrfToken
		},
		success : function (result) {

		    var datas = result.data;

		    //公司logo
		    $("#gslogo").attr("src", datas.logo);
		    $("#shopbanner").attr("src", datas.banner);
			//公司id、名称
			$("#gsid").val(datas.id);
			$("#gsmc").html(datas.company);
			$("#gsemail").html(datas.company_email);
			
			//法人
			$("#legal").val(datas.legal);
			//法人性别：1男,0女
            $("#gender-"+datas.legal_gender).prop("checked", true);
            
			//法人身份证
			$("#identification_number").val(datas.identification_number);
			//选中 省下拉框
            $("#province").attr("def-id", datas.provid);
            $("#province").val(datas.provid).trigger("change");
			//选中 市下拉框, TODO,
			// $("#city").val(datas.cityid);
            $("#city").attr("def-id", datas.cityid);
			//选中 区下拉框
			// $("#country").val(datas.areaid);
            $("#country").attr("def-id", datas.areaid);
            
			//详细地址
			$("#address").val(datas.address);
			//联系人电话
			$("#contact_phone").val(datas.contact_phone);
			//email
			$("#email").val(datas.email);
			//联系人
			$("#contact_person").val(datas.contact_person);
            
			//联系人性别：0保密、1男、2女
			if(datas.lxrsex == 0){
				$("#sexsec").prop("checked",true);
			}else if(datas.lxrsex == 1){
				$("#sexsir").prop("checked",true);
			}else{
				$("#sexgirl").prop("checked",true);
			}
            
			//qq
			$("#qq").val(datas.qq);
            
            // 选择主营类别
            var catagoryAry = [];
            var catagoryStr = "";
            var catagoryTxtAry = [];
            
            _.each(datas.categoryData, function(item){
                catagoryAry.push(item.id);
                catagoryTxtAry.push(item.text);
            });
            catagoryStr = catagoryAry.join(",");
            // hidden input标签赋值
            $("#main_category").val(catagoryStr);
            // 已选类别,
            addSelItems("sel-categ-box", catagoryTxtAry);
            
            // 选择主营品牌
            var brandAry = [];
            var brandStr = "";
            var brandTxtAry = [];
            _.each(datas.brandData, function(item){
                brandAry.push(item.id);
                brandTxtAry.push(item.text);
            });
            brandStr = brandAry.join(",");
            
            $("#main_brand").val(brandStr);
            addSelItems("sel-brand-box", brandTxtAry);
            
            // 电子文件-图片;regist-elec-docs
            var eleFiles = $.extend(["","" ,"","" ,"","" ,"","" ,"",""], datas.elecFiles);
            $("#regist-elec-docs").find("img").each(function(i, ele){
                var imgurl = eleFiles[i] || "";
                if(imgurl != ""){
                    $(this).attr("src", imgurl).parent().css("background-image","none");
                }
            });
		},
		error : function () {
		    var conf = {
		        title : "注意",
		        message : "获取公司资料失败!",
		        ok_txt : "确定"
		    };
		    commTemplUtil.showErrorDialog(conf);
		}
	});
	
	// 选择主营类别
	$("#category-btn").on("click", function () {
		if (typeof PAGE_DATA.modalCategoryData == 'undefined') {
			$.ajax({
				url : PAGE_CONFIG.requestUrl.categoryUrl, 
				type : 'get',
				dataType : 'json',
				success : function (result) {
					PAGE_DATA.modalCategoryData = $.extend([], result.data);
					CreateModalCateg(PAGE_DATA.modalCategoryData).showModal();
				},
				error : function (xhr, status, error) {
					CreateModalCateg([]).showModal();
				}
			});

		} else {
			CreateModalCateg(PAGE_DATA.modalCategoryData).showModal();
		}

	});
	
	// 选择主营品牌;
	$("#brand-btn").on("click", function () {
		if (typeof PAGE_DATA.modalBrandData == 'undefined') {
			$.ajax({
				url : PAGE_CONFIG.requestUrl.brandUrl,
				type : 'get',
				dataType : 'json',
				success : function (result) {
					PAGE_DATA.modalBrandData = $.extend([], result.data);
					CreateModalBrand(PAGE_DATA.modalBrandData).showModal();
				},
				error : function (xhr, status, error) {
					CreateModalBrand([]).showModal();
				}
			});
		} else {
			CreateModalBrand(PAGE_DATA.modalBrandData).showModal();
		}
	});
	
	//渲染tab切换
	$.commNavTabs2($("#commTabs_1").find(".head-item"), 
            $("#commTabs_1").find(".body-item"),
            "current");
	
	// 公司头像选择文件, 
	$("#subLogo").on("click", function () {
		var fileObj = $(this).parent().find("[type='file']");
		fileObj[0].click();
	});
	
	// 公司头像临时 预览图片,
	$("#logo-input").AjaxFileUpload({
	    action : PAGE_CONFIG.requestUrl.uploadimg,
	    name : PAGE_CONFIG.requestUrl.preViewImg,
	    onComplete : function (filename, response) {
	        $("#gslogo").attr("src", response.data);
	    }
	});
    
    // 店铺banner 选择图片文件.
    $("#upload-banner-btn").on("click", function () {
		var fileObj = $(this).parent().find("[type='file']");
		fileObj[0].click();
	});
    
    // 店铺banner 临时预览图片
    $("#banner-input").AjaxFileUpload({
	    action : PAGE_CONFIG.requestUrl.uploadimg,
	    name : PAGE_CONFIG.requestUrl.preViewImg,
	    onComplete : function (filename, response) {
	        $("#shopbanner").attr("src", response.data);
	    }
	});
	
	// 公司资质选择文件
	$("#regist-elec-docs").on("click", ".box-list-image", function () {
		var fileObj = $(this).find("[type='file']");
		fileObj[0].click();
	});
	
	// 公司资质零时预览图片,
	$("#regist-elec-docs").find("[type='file']").each(function(){
		$(this).AjaxFileUpload({
			action : PAGE_CONFIG.requestUrl.uploadimg,
			name : PAGE_CONFIG.requestUrl.preViewImg,
			onComplete : function(filename, response){
				$(this).parent().find("img").attr("src", response.data);
			}
		});		
	});
}


//市
function renderAddrCity(provinceCode) {

	// 市
	$.ajax({
		url : PAGE_CONFIG.requestUrl.addrCity,
		type : 'post',
		dataType : 'json',
		data : {
			code : provinceCode,
			_token : COMM_DATA.csrfToken
		},
		success : function (result) {
			var datas = $.extend([], result.data);
			var tmplObjHtml = areaTemplObj(datas);
			$("#city").html(tmplObjHtml);
            
            if($("#city").attr("def-id") != ""){
               // 页面初始化.
               var defVal = $("#city").attr("def-id");
               $("#city").attr("def-id", "").val(defVal).trigger("change");
            }

		},
		error : function (xhr, status, error) {
			var tmplObjHtml = areaTemplObj([]);
			$("#city").html(tmplObjHtml);
		}
	});
	
	$("#city").empty().html(areaTemplObj([]));
	$("#country").empty().html(areaTemplObj([]));
};
//区/县
function renderAddrCounty(cityCode) {
	// 区/县
	$.ajax({
		url : PAGE_CONFIG.requestUrl.addrCounty,
		type : 'post',
		dataType : 'json',
		data : {
			code : cityCode,
			_token : COMM_DATA.csrfToken
		},
		success : function (result) {
			var datas = $.extend([], result.data);
			var tmplObjHtml = areaTemplObj(datas);
			$("#country").html(tmplObjHtml);
            
            if($("#country").attr("def-id") != ""){
               // 页面初始化.
               var defVal = $("#country").attr("def-id");
               $("#country").attr("def-id", "").val(defVal);
            }
		},
		error : function (xhr, status, error) {
			var tmplObjHtml = areaTemplObj([]);
			$("#country").html(tmplObjHtml);
		}
	});
};

/*
 *  主营类别
 */
function CreateModalCateg(data) {

	// item-template
	var tmplObj = _.template($('#item-template').html());
	var tmplObjHtml = tmplObj(data);

	// 模态框, 选择主营类别 category-btn，
	var dial = dialog({
			id : "dialog-categ",
			width : 550,
			height : 400,
			title : "选择类别",
			content : tmplObjHtml,
			onshow : function () {
				// bind event
				var that = this;

				// bind event
				var dialogObj = $("[id='content:dialog-categ']");
				dialogObj.find(".info-item").on("click", function () {
					var id = $(this).attr("id");
					var start = id.lastIndexOf("-");
					var idx = id.substr(start + 1);
					$(this).addClass("hover").siblings().removeClass("hover");
					$("#info-detail-box-" + idx).show().siblings().hide();
				});

				// dialogObj.find(":checkbox");
				var codeStr = $("#main_category").val();
				var codeAry = codeStr.split(",");

				_.each(codeAry, function (item) {
					dialogObj.find(":checkbox").filter("[code='" + item + "']").attr("checked", true);
				});

				//保存
				$("#modal-save-btn").on("click", function () {
					var codeAry = [];
					var txtAry = [];
					dialogObj.find(":checked").each(function () {
						codeAry.push($(this).attr("code"));
						txtAry.push($(this).attr("txt"));
					});
					$("#main_category").val(codeAry.join(","));

					addSelItems("sel-categ-box", txtAry);

					that.remove();
				});

				// 初始化 显示设定;
				$("#info-item-title-0").addClass("hover");
				$("#info-detail-box-0").show();
			}
		});

	return dial;
};
/*
 * 主营品牌
 */
function CreateModalBrand(data) {
	// item-template
	var tmplObj = _.template($('#item-template').html());
	var tmplObjHtml = tmplObj(data);

	// 模态框, 选择主营类别
	var dial = dialog({
			id : "dialog-brand",
			width : 550,
			height : 400,
			title : "选择品牌",
			content : tmplObjHtml,
			onshow : function () {

				var that = this;
				// bind event
				var dialogObj = $("[id='content:dialog-brand']");
				dialogObj.find(".info-item").on("click", function () {
					var id = $(this).attr("id");
					var start = id.lastIndexOf("-");
					var idx = id.substr(start + 1);
					$(this).addClass("hover").siblings().removeClass("hover");
					$("#info-detail-box-" + idx).show().siblings().hide();
				});

				// 渲染已选择项
				var codeStr = $("#main_brand").val();
				var codeAry = codeStr.split(",");
				_.each(codeAry, function (item) {
					dialogObj.find(":checkbox").filter("[code='" + item + "']").attr("checked", true);
				});

				//保存
				$("#modal-save-btn").on("click", function () {
					var codeAry = [];
					var txtAry = [];
					dialogObj.find(":checked").each(function () {
						codeAry.push($(this).attr("code"));
						txtAry.push($(this).attr("txt"));
					});
					$("#main_brand").val(codeAry.join(","));

					addSelItems("sel-brand-box", txtAry);

					that.remove();
				});

				// 初始化 显示设定;
				$("#info-item-title-0").addClass("hover");
				$("#info-detail-box-0").show();
			}

		});

	return dial;
};

//验证公司基本资料及表单提交
function validateMainForm(){
	// 添加 验证逻辑;
	var formValidate = $("#mainform").validate({
			rules : {
				legal : "required",
				identification_number : "required",
				province : "required",
				city : "required",
				country : "required",
				address : "required",
				contact_phone : "required",
				email : {
					required : true,
					email : true
				},
				contact_person : "required",
				// qq : "required"
			},
			errorPlacement : function (error, element) {
				if (element.attr("type") == "text") {
					element.after($("<span class='error-line'  align='center'/>").append(error));
				}
			}
		});
	
	// 资料提交申请
	$("#zl-submit-btn").on("click", function () {
		if(!formValidate.form()){
			return false;
		}
		$("#mainform").submit();
		
	});
}

//验证修改密码的表单及提交
function validatePwdForm(){
	// 修改密码-提交
	$("#subPwd").on("click", function () {
		//表单验证规则
		var valiForm = $("#myform1").validate({
			rules : {
				oldpwd : "required",
				newpwd : "required",
				confirmpwd:"required"
			},
			errorPlacement : function (error, element) {
				if (element.attr("type") == "text" || element.attr("type") == "password" ) {
					element.after($("<span class='error-line'  align='center'/>").append(error));
				}
			}
		});
		
		//验证表单
		var flag = valiForm.form();
		if (!flag) {
			return false;
		}
		
		var form = $("#myform1");

		//旧密码
		var oldpwd = form.find("input[name='oldpwd']").val();
		//新密码
		var newpwd = form.find("[name='newpwd']").val();
		//确认新密码
		var confirmpwd = form.find("[name='confirmpwd']").val();
		//判断新密码与确认新密码是否一致
		if (confirmpwd != newpwd) {
			var conf = {
				title : "注意",
				message : "两次密码输入不符!",
				ok_txt : "确定"
			};
			commTemplUtil.showErrorDialog(conf);
			return false;
		}
		
		//提交请求
		$.ajax({
			url : PAGE_CONFIG.requestUrl.editpwd,
			type : "put",
			data : {
				oldpwd : oldpwd,
				newpwd : newpwd,
				_token : COMM_DATA.csrfToken
			},
			success : function (result) {
				if(result.data.msg == 1){
					var conf = {
							title : "注意",
							message : "修改密码成功!",
							ok_txt : "确定"
						};
							commTemplUtil.showErrorDialog(conf);
				}else{
					var conf = {
							title : "注意",
							message : "修改密码失败!",
							ok_txt : "确定"
						};
							commTemplUtil.showErrorDialog(conf);
				}
				
			},
			error : function () {
				var conf = {
						title : "注意",
						message : "修改密码失败!",
						ok_txt : "确定"
					};
						commTemplUtil.showErrorDialog(conf);
			}
		});
	});
}

//验证修改密码的表单及提交
function validateEmailForm(){
	// 修改邮件-提交
	$("#editEmail").on("click", function () {
		//表单验证规则
		var valiForm = $("#myform2").validate({
			rules : {
				pwd : "required",
				email : {
					required : true,
					email : true
				}
			},
			errorPlacement : function (error, element) {
				if (element.attr("type") == "text" || element.attr("type") == "password" ) {
					element.after($("<span class='error-line'  align='center'/>").append(error));
				}
			}
		});
		
		//验证表单
		var flag = valiForm.form();
		if (!flag) {
			return false;
		}
		
		var form = $("#myform2");

		//密码
		var pwd = form.find("input[name='pwd']").val();
		//邮件
		var email = form.find("[name='email']").val();
		//提交请求
		$.ajax({
			url : PAGE_CONFIG.requestUrl.editemail,
			type : "put",
			data : {
				pwd : pwd,
				email : email,
				_token : COMM_DATA.csrfToken
			},
			success : function (result) {
			    var conf = {
			        title : "注意",
			        message : "修改电子邮箱成功!",
			        ok_txt : "确定"
			    };
			    commTemplUtil.showErrorDialog(conf);
			},
			error : function (result) {
			    // result = Object {readyState: 4, responseText: "{"data":"\u5bc6\u7801\u9519\u8bef"}",
			    // responseJSON: Object, status: 403, statusText: "Forbidden"}
			    var conf = {
			        title : "注意",
			        message : "修改电子邮箱失败!",
			        ok_txt : "确定"
			    };

			    var dataJson = $.extend({}, result.responseJSON);

			    if (!!dataJson.data && dataJson.data.length > 0) {
			        conf.message = dataJson.data;
			    }

			    commTemplUtil.showErrorDialog(conf);
			}
		});
	});
}

//选择主营类别
function addSelItems(containerId, data) {
	var tmplObj = _.template($('#sel-item-templ').html());
	var tmplObjHtml = tmplObj(data);
	$("#" + containerId).html(tmplObjHtml);
};